var React = require('react');
var TableRow = require('./TableRow');

module.exports = React.createClass({
	displayName:'TableBody',
	getInitialState:function(){
		return {
			curr: null,
			data: null
		}
	},
	componentDidMount:function(){
		this._dataSource = Store.dataSource(this.props.data, {
			autoLoad: this.props.autoLoad||true,
			onSuccess: function (data){
				console.log('TableBody', data);
				this.__onDataLoaded(data.result || data);
			}.bind(this)
		});
	},
	refresh: function (){
		this._dataSource.refresh();
	},
	setData: function (data, argv){
		this._dataSource.reset(data, argv);
	},
	addRow: function (row){
		this.state.data.push(row);
		this.setState({
			state: this.state.data
		});
	},
	__onDataLoaded: function (data){
		this.setState({ data: data });
		if(this.props.fireIndex != undefined){
			this.fireClick(this.props.fireIndex);
		}
		this.props.onLoaded && this.props.onLoaded(data, this);
	},
	fireClick: function (index){

	},
	setAllChecked: function (value){
		this._rows.map(function (row, index){
			row.checked(value);
		});
	},
	getCheckedItems: function (filter){
		var _values = [];
		this._rows.map(function (row, index){
			if(filter&&filter(row, index)!==false){
				// idle
			} else {
				if(row._checked){
					_values.push(row);
				}
			}
		});

		return _values;
	},
	__onRowDidMount: function (row){
		this._rows.push(row);
	},
	__onTableRowClick: function (event, data, row) {
		if(this.state.curr){
			this.state.curr.selected(false);
		}
		row.selected(true);
		this.state.curr = row;
	},
	render:function(){
		this._rows = [];
		return (
			<tbody>
				{
					this.state.data && this.state.data.map(function (item, index){
						return <TableRow
									key={index}
									data={item}
									editable={item._editable}
									checkbox={this.props.checkbox}
									rowRender={this.props.rowRender}
									columnRender={this.props.columnRender}
									onDidMount={this.__onRowDidMount}
									onRowClick={this.__onTableRowClick}
									onCheckBoxChange={this.props.onCheckBoxChange}
									items={this.props.items}/>
					}.bind(this))
				}
			</tbody>
		);
	}
});
